import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get_utils/src/platform/platform.dart';
import 'package:permission_handler/permission_handler.dart';

import 'index.dart';

/// 授权返回
class PrivilegeStatus {
  final bool result;
  final String message;

  PrivilegeStatus({required this.result, required this.message});
}

/// 动态授权
class Privilege {
  /// 是否有相册权限
  static Future<PrivilegeStatus> photos() async {

    // 相册权限
    String localKey = 'Permission.photos';
    bool isShow = false;// 是否展示了弹窗
    // 获取提示信息
    Map? data = permissionWarning(Permission.photos);
    if (data != null) {
      isShow = OverlayTipUtil.to.show(
        localKey: localKey,
        title: data['title'],
        body: data['body'],
      );
    }

    var value = false;
    bool isDenied = false;// 是否为永久拒绝
    if (GetPlatform.isIOS) {
      var statues = await [Permission.photos].request();
      var photosStatus = statues[Permission.photos];
      // 是否有权限
      value = photosStatus == PermissionStatus.granted;
      // 是否完全拒绝
      isDenied = photosStatus == PermissionStatus.permanentlyDenied;
    }

    if (GetPlatform.isAndroid) {
      // Android需要文件存储权限
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      if (androidInfo.version.sdkInt <= 32) {
        var statues = await [Permission.storage].request();
        var storageStatus = statues[Permission.storage];
        print('===安卓相册(storageStatus)====$storageStatus');
        value = storageStatus == PermissionStatus.granted;
        // 是否完全拒绝
        isDenied = storageStatus == PermissionStatus.permanentlyDenied;
      }  else {
        var statues = await [Permission.photos].request();
        var photosStatus = statues[Permission.photos];
        print('===安卓相册(photosStatus)====$photosStatus');
        // 是否有权限
        value = photosStatus == PermissionStatus.granted;
        // 是否完全拒绝
        isDenied = photosStatus == PermissionStatus.permanentlyDenied;
      }
    }

    // 隐藏弹窗
    if (isShow) OverlayTipUtil.to.hideOverlay();
    // 持久化保存，不在展示提示框
    Storage().setBool(localKey,  isDenied);

    return PrivilegeStatus(
      result: value,
      message: value ? 'ok' : '请您去设置中开启相册访问权限',
    );
  }

  /// 是否有相机权限(拍摄视频需要使用麦克风权限)
  static Future<PrivilegeStatus> camera({required bool isVideo}) async {

    var permissions = <Permission>[Permission.camera];

    // 拍摄视频需要麦克风权限(相机拍照不需要)
    if (isVideo) permissions.add(Permission.microphone);
    if (GetPlatform.isIOS) {
      // iOS需要申请相册访问权限
      permissions.add(Permission.photos);
    }
    if (GetPlatform.isAndroid) {
      // Android需要文件存储权限
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      if (androidInfo.version.sdkInt <= 32) {
        permissions.add(Permission.storage);
      }  else {
        permissions.add(Permission.photos);
      }
    }

    // 相机权限
    String localKey = 'Permission.camera';
    bool isShow = false;// 是否展示了弹窗
    // 获取提示信息
    Map? data = permissionWarning(Permission.camera);
    if (data != null) {
      isShow = OverlayTipUtil.to.show(
        localKey: localKey,
        title: data['title'],
        body: data['body'],
      );
    }

    // 申请所需要的权限
    var statues = await permissions.request();
    // 隐藏弹窗
    if (isShow) OverlayTipUtil.to.hideOverlay();
    // 持久化保存，不在展示提示框
    Storage().setBool(localKey,  statues[Permission.camera] == PermissionStatus.permanentlyDenied);

    // 记录权限申请结果
    bool result = true;
    String msg = 'ok';

    // 遍历结果
    for (var entry in statues.entries) {
      var key = entry.key;
      var value = entry.value;
      // 无权限结束循环
      if (value != PermissionStatus.granted && result == true) {
        debugPrint('====无权限名称:$key====权限结果:$value');
        result = false;// 标记无权限
        if (key == Permission.photos){
          msg = '请您去设置中开启相册访问权限';
        }else if (key == Permission.camera){
          msg = '请您去设置中开启相机使用权限';
        }else if (key == Permission.microphone){
          msg = '请您去设置中开启麦克风使用权限';
        }else if (key == Permission.storage){
          msg = '请您去设置中开启文件存储权限';
          result = true;// 安卓忽略文件存储权限(不分机型不适配，暂时忽略)
        }
        break;
      }
    }
    return PrivilegeStatus(
      result: result,
      message: msg,
    );
  }

  /// 是否有麦克风权限
  static Future<PrivilegeStatus> microphone() async {

    // 麦克风权限
    String localKey = 'Permission.microphone';
    bool isShow = false;// 是否展示了弹窗
    // 获取提示信息
    Map? data = permissionWarning(Permission.microphone);
    if (data != null) {
      isShow = OverlayTipUtil.to.show(
        localKey: localKey,
        title: data['title'],
        body: data['body'],
      );
    }

    var statues = await [Permission.microphone].request();
    // 隐藏弹窗
    if (isShow) OverlayTipUtil.to.hideOverlay();
    // 持久化保存，不在展示提示框
    Storage().setBool(localKey,  statues[Permission.microphone] == PermissionStatus.permanentlyDenied);

    var value = statues[Permission.microphone] == PermissionStatus.granted;

    return PrivilegeStatus(
      result: value,
      message: value ? 'ok' : '请您去设置中开启麦克风使用权限',
    );
  }

  /// 是否有存储权限
  static Future<bool> storage() async {
    bool value = false;
    String text = '';
    if (GetPlatform.isAndroid) {
      value = await Permission.storage.request().isGranted;
      text = '请您去设置中开启文件存储权限';
    }
    if (GetPlatform.isIOS) value = true;
    if (!value) {
      Loading.toast(text);
      await Future.delayed(const Duration(seconds: 2));
      openSettings();
    }
    return value;
  }

  /// 打开系统设置
  static Future<bool> openSettings() async {
    return await openAppSettings();
  }

  /// 系统权限提示信息
  static Map? permissionWarning (var key) {

    if (key == Permission.photos){
      // 相册访问权限
      return {
        'title':'"同城速约"想访问您的媒体文件',
        'body':'为了您能正常分享图片/视频、保存图片/视频，"同城速约"需要申请存储权限。如您拒绝授权，不影响您使用APP的其他功能。',
      };
    } else if (key == Permission.camera){
      // 相机使用权限
      return {
        'title':'"同城速约"想访问您的相机',
        'body':'为了您能正常体验拍照、录制视频，"同城速约"需要申请相机权限。如您拒绝授权，不影响您使用APP的其他功能。',
      };
    } else if (key == Permission.microphone){
      // 麦克风使用权限
      return {
        'title':'"同城速约"想访问您的麦克风',
        'body':'为了您能正常体验录音、录制视频，"同城速约"需要申请麦克风权限。如您拒绝授权，不影响您使用APP的其他功能。',
      };
    }
    return null;
  }

}
